package de.jmda.core.util.ramcomp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

import javax.tools.SimpleJavaFileObject;

/**
 * Represents an in memory java byte code file.
 *
 * @author roger@jmda.de
 */
public class JavaByteCodeObject extends SimpleJavaFileObject
{
	/**
	 * Represents java byte code.
	 */
	protected final ByteArrayOutputStream byteCode = new ByteArrayOutputStream();

	/**
	 * Creates <code>string:///</code> {@link URI} based on <code>classname</code>
	 * and calls super constructor with that.
	 *
	 * @param classname Qualified name of the public class in {@link #byteCode}.
	 * @param kind Kind of the data in {@link #byteCode} (will be {@link
	 *             Kind#CLASS}).
	 */
	public JavaByteCodeObject(String classname, Kind kind)
	{
		super(
				URI.create("string:///" + classname.replace('.', '/') + kind.extension),
		    kind);
	}

	/**
	 * @return byte array for {@link #byteCode}
	 */
	public byte[] getBytes()
	{
		return byteCode.toByteArray();
	}

	/**
	 * @return {@link #byteCode} to allow e.g. a compiler to write its output.
	 */
	@Override
	public OutputStream openOutputStream() throws IOException
	{
		return byteCode;
	}
}